package today.rocky.boot.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import today.rocky.boot.security.entity.UserInfo;
import today.rocky.boot.security.service.UserInfoService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Rocky
 * @version 1.0
 * @date 2020/5/13 10:16
 */
@Component
public class CustomUserDetailService implements UserDetailsService {

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		/**
		 * 1/通过username 获取到userinfo信息
		 * 2/通过user(UserDetails)返回UserDetails
		 */
		UserInfo userInfo = userInfoService.findByUsername(s);

		if(userInfo == null){
			throw new UsernameNotFoundException("not found");
		}

		List<GrantedAuthority> authorities = new ArrayList<>();
		authorities.add(new SimpleGrantedAuthority("ROLE_"+userInfo.getRole().name()));
		authorities.forEach(System.out::println);
		return new User(userInfo.getUsername(),passwordEncoder.encode(userInfo.getPassword()),authorities);
	}
}
